import { defineStore } from 'pinia';
import { getToken, saveToken, removeToken } from '@/utils/auth';
import { wxLogin, getRouters, getInfo, login } from '@/api/login.js';
import env from '@/env'

// 定义一个 store
export const useAuthStore = defineStore('auth', {
  // 状态
  state: () => ({
    logined: false,
    userInfo: {
      token: getToken()
    },
    // 群聊选择用户
    chatUsers: [],
	userId:'',
	bannerImage:'https://www.zxsl.zxmap.cn/zxch-app/2025/04/16/7a6d7b180c3d43c7a0aacc64828aee4c.png'
  }),
  // 获取器
  // getters: {
  //   token: (state) => state.userInfo.token,
  //   userInfo: (state) => state.userInfo,
  //   logined: (state) => state.logined,
  //   chatUsers: (state) => state.chatUsers
  // },
  // 动作
  actions: {
	// 微信登录
	async wxLogind (e, openidCode) {
	  // const { data: { code, data, msg } }  = await wxLogin({ 'xcxCode': e, 'code': openidCode,'clientId': env.VITE_APP_CLIENT_ID, 'grantType':"xcx", "tenantId": "000000" });
	  const { code, data, msg } = await wxLogin({ 'xcxCode': e, 'code': openidCode,'clientId': env.VITE_APP_CLIENT_ID, 'grantType':"xcx", "tenantId": "000000" });
	  if (code !== 200) {
		uni.showToast({ title: msg, icon: 'none' });
		return;
	  }
	  if (data && data.access_token) {
		this.logined = true;
		this.userInfo.token = data.access_token;
		uni.setStorageSync('isLogined', true);
		saveToken(data.access_token)
		this.getInfoData();
		uni.showToast({ title: '登录成功', icon: 'none' });
		setTimeout(() => {
			uni.switchTab({
				url:'/pages/index/index'
			});
		}, 1000);
	  }
	},
	// 微信登录
	async Logind (e, openidCode) {
	  const { code, data, msg } = await wxLogin(e);
	  if (code !== 200) {
		uni.showToast({ title: msg, icon: 'none' });
		return;
	  }
	  if (data && data.access_token) {
		this.logined = true;
		this.userInfo.token = data.access_token;
		uni.setStorageSync('isLogined', true);
		saveToken(data.access_token)
		this.getInfoData();
		uni.showToast({ title: '登录成功', icon: 'none' });
		setTimeout(() => {
			uni.switchTab({
				url:'/pages/index/index'
			});
		}, 1000);
	  }
	},
	async getInfoData() {
		const res= await getInfo();
		if (res.code === 200) {
			uni.setStorageSync("loginInfo", res.data);
			this.userId = res.data.user.userId;
		}
	},
    login(userInfo) {
      // console.log(userInfo, 'userinfo set')
      this.logined = true;
      this.userInfo.token = userInfo.token;
      uni.setStorageSync('isLogined', true);
      saveToken(userInfo.token);
    },
    logout() {
      this.logined = false;
      uni.setStorageSync('isLogined', false);
      this.userInfo = {};
      removeToken();
    },
    setChatUsers(userIds) {
      this.chatUsers = userIds;
    },
    clearChatUsers() {
      this.chatUsers = [];
    }
  }
});